package cn.lml.lession.filter;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.client.resource.UserRedirectRequiredException;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.stereotype.Component;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

@Component
public class AccessTokenFilter extends ZuulFilter {
	
	private static final String AUTHORIZATION_HEADER = "Authorization";
	private static final String BEARER_TOKEN_TYPE = "bearer";
	
	@Autowired
	public OAuth2RestTemplate oAuth2RestTemplate;

	@Override
	public String filterType() {
		return FilterConstants.ROUTE_TYPE;
	}

	@Override
	public int filterOrder() {
		return FilterConstants.PRE_DECORATION_FILTER_ORDER + 1;
	}

	@Override
	public boolean shouldFilter() {
		return true;
	}

	@Override
	public Object run() {
		RequestContext context = RequestContext.getCurrentContext();
		//Object originalRequestPath = context.get(FilterConstants.REQUEST_URI_KEY);
		String accessToken=null;
		try{
			accessToken =oAuth2RestTemplate.getAccessToken().toString();
		}catch(UserRedirectRequiredException e){
		}
		if(StringUtils.isNotBlank(accessToken))context.addZuulRequestHeader(AUTHORIZATION_HEADER,
				String.format("%s %s", BEARER_TOKEN_TYPE, accessToken));
	
		return null;
	}
}